package com.linghang.association.service;
import com.linghang.association.domain.Message;
import com.linghang.association.domain.MessageExample;
import com.linghang.association.mapper.MessageMapper;
import com.linghang.association.mapper.UserMapper;
import com.linghang.association.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
 * @author LinyaT052
 * @date 2022年07月21日 10:07
 * 实时消息推送逻辑实现层
 */
@Service
public class MessageService {
    //注入userMapper类
    @Resource
    private UserMapper userMapper;
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private WebSocketServer webSocketServer;
    private Logger LOG = LoggerFactory.getLogger(MessageService.class);
    /**
     * 报名成功推送消息
     * @param departmentId
     */
    public void pushToAdmin(Integer departmentId) {
        LOG.info("部门id为"+departmentId);
        String username = userMapper.selectAdmin(departmentId);
        String message = "尊敬的管理员:"+username+"您收到一条新的报名申请，请及时查看并审核！";
        webSocketServer.sendInfo(username,message);
    }
    /**
     * 报名申请成功处理推送消息
     * @param username
     */
    public void pushToUser(String username) {
        LOG.info("用户姓名为"+username);
        String message = "亲爱的同学:"+username+"您的报名请求已成功由管理员处理，请及时查看结果！";
        webSocketServer.sendInfo(username,message);
    }
    /**
     * 检查是否有离线消息
     * @param username
     */
    public int offlinePush(String username) {
        MessageExample example = new MessageExample();
        MessageExample.Criteria criteria = example.createCriteria();
        //添加查询条件
        criteria.andUsernameEqualTo(username);
        //从数据库查询该用户
        List<Message> messages = messageMapper.selectByExample(example);
        System.out.println(messages);
        int size = 0;
        for(Message m:messages){
            webSocketServer.sendInfo(username,m.getMessage());
            //发送一条删除一条
            messageMapper.deleteByPrimaryKey(m.getId());
            size++;
        }
        return size;
    }

}
